package com.justgame.project.cloud.common.constant;

import com.justgame.project.cloud.common.util.ObjUtil;
import lombok.SneakyThrows;
import org.apache.commons.lang3.CharSequenceUtils;

import java.io.Serializable;
import java.lang.invoke.SerializedLambda;
import java.lang.reflect.Method;
import java.util.function.Function;

public interface SerializableFunction<T,R> extends Serializable, Function<T,R> {

    @SneakyThrows
    default SerializedLambda getSerializedLambda(){
        Method write = this.getClass().getDeclaredMethod("writeReplace");
        write.setAccessible(true);
        return (SerializedLambda) write.invoke(this);
    }

    default String getImplClass() {
        try {
            return getSerializedLambda().getImplClass();
        } catch (Exception e) {
            return null;
        }
    }

    default String getImplMethodName() {
        try {
            return getSerializedLambda().getImplMethodName();
        } catch (Exception e) {
            return null;
        }
    }

    default String getFieldName(){
        String methodName = getImplMethodName();
        if (methodName.startsWith("get")){
            methodName = methodName.substring(3);
        }
        return methodName.substring(0,1).toLowerCase() + methodName.substring(1);
    }

    @SneakyThrows
    default Class<?> getFieldType(){
        SerializedLambda serializedLambda = getSerializedLambda();
        Class<?> clazz = Class.forName(serializedLambda.getImplClass().replace("/","."));
        Method method = clazz.getMethod(getImplMethodName());
        return method.getReturnType();
    }
}
